def longest_common_subsequence(text1, text2):
    m, n = len(text1), len(text2)
    # dp[i][j] 表示 text1[0:i] 和 text2[0:j] 的LCS长度
    dp = [[0] * (n + 1) for _ in range(m + 1)]
    
    # 构建DP表
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if text1[i-1] == text2[j-1]:
                dp[i][j] = dp[i-1][j-1] + 1
            else:
                dp[i][j] = max(dp[i-1][j], dp[i][j-1])
    
    # 回溯找出LCS
    lcs = []
    i, j = m, n
    while i > 0 and j > 0:
        if text1[i-1] == text2[j-1]:
            lcs.append(text1[i-1])
            i -= 1
            j -= 1
        elif dp[i-1][j] > dp[i][j-1]:
            i -= 1
        else:
            j -= 1
    
    return dp[m][n], ''.join(lcs[::-1])

# 测试
text1 = "ABCDGH"
text2 = "AEDFHR"
length, lcs_str = longest_common_subsequence(text1, text2)

print(f"\n最长公共子序列：")
print(f"序列1: {text1}")
print(f"序列2: {text2}")
print(f"LCS长度: {length}")
print(f"LCS字符串: {lcs_str}")

# 另一个例子
text1 = "AGGTAB"
text2 = "GXTXAYB"
length, lcs_str = longest_common_subsequence(text1, text2)
print(f"\n序列1: {text1}")
print(f"序列2: {text2}")  
print(f"LCS长度: {length}")
print(f"LCS字符串: {lcs_str}")